//
//  JYRegisterController.m
//  JYFarm
//
//  Created by 花花 on 2017/10/12.
//  Copyright © 2017年 花花. All rights reserved.
//

#import "JYRegisterController.h"
#import "JYLoginController.h"
#import "JYSettingPwdView.h"
#import "JYSetingPwdController.h"
#import "BaseNavViewController.h"
#import "JYShopsInfoController.h"
@interface JYRegisterController (){
    
    UIButton * _smsCodeBtn;
    
    BOOL _isSetingPwd;
    
    NSString *codeStr; //验证码
}
@property(nonatomic)JYSettingPwdView *accountTextFiled;//手机号

@property(nonatomic)JYSettingPwdView *pwdTextField;//新密码

@property(nonatomic)JYSettingPwdView *rePwdTextField;//请输入验证码

@property(nonatomic)JYSettingPwdView *verificationTextField;//请输入邀请码

@property(nonatomic)UIView *bgView;
@end

@implementation JYRegisterController

- (instancetype)initWithIsSetingPwd:(BOOL)isSetingPwd{
    
    if (self = [super init]) {
        _isSetingPwd = isSetingPwd;
    }
    return self;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupNav];
    
    [self setupSubView];
    
    
}
#pragma mark - setupNav
- (void)setupNav{
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.title = @"注册";
    
}
- (void)setupSubView{
    
    CGFloat margin = 0;
    CGFloat height = kGlobalButtonHeight;
    CGFloat padding = 0;
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_Width, height *4)];
    bgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bgView];
    _bgView = bgView;

    //用户名
    self.accountTextFiled = [self registerFrame:CGRectMake(margin, 0, Screen_Width - margin *2 , height) placeholder:@"请输入手机号" leftImgName:@"login_mobile_number"];

    //密码
    self.pwdTextField = [self registerFrame:CGRectMake(margin, CGRectGetMaxY(self.accountTextFiled.frame)+padding,Screen_Width - margin *2 , height) placeholder:@"请输入新密码" leftImgName: @"login_password"];
    
        //请输入验证码
    self.verificationTextField =  [self registerFrame:CGRectMake(margin, CGRectGetMaxY(self.pwdTextField.frame)+padding, Screen_Width - margin *2 , height) placeholder:@"请输入验证码" leftImgName:@"login_verification_code_icon"];
    self.verificationTextField.inputTextFiled.clearButtonMode = UITextFieldViewModeNever;
        [self.bgView addSubview:self.verificationTextField];
        //获取验证码
        
        UIButton *getSmsBtn =[UIButton jy_buttontitle:@"获取验证码" titleColor:kThemeColor frame:CGRectMake(Screen_Width -90-15,10 , 90, 30 ) target:self action:@selector(getsmsCodeBtnOnClick:) fontSize:14 bgImageName:@"login_verification_code"];
        getSmsBtn.tag = 10;
        [self.verificationTextField addSubview:getSmsBtn];
    
    
    //确认密码
    self.rePwdTextField  = [self registerFrame:CGRectMake(margin, CGRectGetMaxY(self.verificationTextField.frame)+padding, Screen_Width - margin *2 , height) placeholder:@"请输入邀请码" leftImgName:@"login_verification_code_icon"];
    
    
    
    
    UIButton *registerBtn = [UIButton jy_buttontitle:@"注册" titleColor:[UIColor whiteColor] frame:CGRectMake(10, CGRectGetMaxY(self.bgView.frame)+30, Screen_Width-20, kBtnHeight) target:self action:@selector(registerOnClick:) fontSize:17 bgImageName:@"login_button_background"];
    [self.view addSubview:registerBtn];
    
    
    UIButton *forgetPwdBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [forgetPwdBtn setTitle:@"忘记密码" forState:UIControlStateNormal];
    [forgetPwdBtn setTitleColor:k6Color forState:UIControlStateNormal];
    forgetPwdBtn.titleLabel.font = kFont(13);
    [forgetPwdBtn addTarget:self action:@selector(forgetPwdOnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:forgetPwdBtn];
    
    [forgetPwdBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.height.mas_equalTo(30);
        make.top.mas_equalTo(registerBtn.mas_bottom).offset(10);
        make.width.mas_equalTo(60);
    }];
    
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [loginBtn setTitle:@"立即登录" forState:UIControlStateNormal];
    [loginBtn setTitleColor:k6Color forState:UIControlStateNormal];
    loginBtn.titleLabel.font = kFont(13);
    [loginBtn addTarget:self action:@selector(loginOnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:loginBtn];
    
    [loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-10);
        make.height.mas_equalTo(30);
        make.top.mas_equalTo(registerBtn.mas_bottom).offset(10);
        make.width.mas_equalTo(60);
    }];
    
    
    
}
- (void)forgetPwdOnClick{
NSLog(@"%s",__func__);

    JYSetingPwdController *setVc = [[JYSetingPwdController alloc]initWithIsSetingPwd:YES];

    [UIView beginAnimations:nil context:NULL];
    //设置动画块中的动画属性的变化的曲线
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    
    //设置持续时间
    [UIView setAnimationDuration:1.0];
    
    /**
     UIViewAnimationTransitionNone, 不使用动画
     UIViewAnimationTransitionFlipFromLeft, 从左向右翻转
     UIViewAnimationTransitionFlipFromRight, 从右向左翻转
     UIViewAnimationTransitionCurlUp,卷曲翻页， 从下往上
     UIViewAnimationTransitionCurlDown, 卷曲翻页， 从上往下
     */
    
    //设置过度的动画效果
    [UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.navigationController.view cache:NO];
    [self.navigationController pushViewController:setVc animated:YES];
    //提交动画
    [UIView commitAnimations];

}
-(void)loginOnClick{

    
    BaseNavViewController *nav  = [[BaseNavViewController alloc]initWithRootViewController:[JYLoginController new]];

    [self  presentViewController:nav animated:YES completion:nil];


   NSLog(@"%s",__func__);
}
//获取验证码
- (void)sendCodeEvent{

    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"phone"] =  self.accountTextFiled.inputTextFiled.text;
    
    param[@"operateType"]= @"1";

    [HTTPRequest POST:kGetSmsCodeUrl parameter:param success:^(id resposeObject) {
        
        NSLog(@"发送验证码……%@",resposeObject);
        
        if (SUCCESS) {
            
            
            
            
        }else{
            
            [MBProgressHUD LY_ShowError:resposeObject[@"msg"] time:2.0];
            
        
            
        }
    } failure:^(NSError *error) {
        
        [MBProgressHUD LY_ShowError:kNoNetworkTips time:2.0];

    }];


}
#pragma mark - SEL Methods
- (void)registerOnClick:(UIButton *)btn{
//    
//    if (![self checkParam]) {
//        return;
//    }
    
    
    
     [self.navigationController pushViewController:[JYShopsInfoController new] animated:YES];
    NSDictionary *param = @{@"userName":self.accountTextFiled.inputTextFiled.text,
                            @"password":[LYTools MD5ForLower32Bate:self.pwdTextField.inputTextFiled.text],
                            @"smsCode":self.rePwdTextField.inputTextFiled.text,
                            @"terminalType":@(2)};
    [HTTPRequest POST:kRegistUrl parameter:param success:^(id resposeObject) {
        NSLog(@"%@",resposeObject);
        if ([resposeObject[@"result"] intValue] == 0) {//注册成功
            
       //    [self.navigationController pushViewController:[JYShopsInfoController new] animated:YES];x
            
        }else{
            [MBProgressHUD LY_ShowError:(resposeObject[@"msg"]) time:2.0];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD LY_ShowError:(kNoNetworkTips) time:2.0];
    }];

    
    

    NSLog(@"%s",__func__);
}
- (void)getsmsCodeBtnOnClick:(UIButton *)btn{
    
    
//    if (![self checkParam]) {
//        return;
//    }
    
    //测试
    [self getPhoneCode:btn];
       [self sendCodeEvent];//发送验证码
//        if (self.accountTextFiled.inputTextFiled.text.length == 0) {
//            [MBProgressHUD LY_ShowError:(@"请输入手机号") time:2.0];
//            return;
//        }
//        if (![self.accountTextFiled.inputTextFiled.text isMobileNumber]) {
//            [MBProgressHUD LY_ShowError:(@"请输入正确的手机号") time:2.0];
//            return;
//        }
//        NSDictionary *params = @{@"account":self.phoneTextF.text,
//                                 @"operateType":@"4",
//                                 @"type":@"2"};
//        LYWeakSelf;
//        [HTTPRequest GET:kFindAccountUrl parameter:params success:^(id resposeObject) {
//    
//            NSLog(@"%@ddddfdfd",resposeObject);
//            if ([resposeObject[@"result"] integerValue] == 0) {
//                [MBProgressHUD LY_ShowError:LYLocalizedString(@"账号不存在") time:2.0];
//            }else if([resposeObject[@"result"] integerValue] == 9 ){
//    
//                [weakSelf sendCodeEvent];//发送验证码
//                [weakSelf getPhoneCode:btn];
//    
//            }else{
//    
//                [MBProgressHUD LY_ShowError:LYLocalizedString(resposeObject[@"msg"]) time:2.0];
//            }
//        } failure:^(NSError *error) {
//    
//            [MBProgressHUD LY_ShowError:LYLocalizedString(kNoNetworkTips) time:2.0];
//        }];
}
- (void)getPhoneCode:(UIButton *)btn{
    __block int MaxTime =kGlobalGetVaildCodeTime;
    _smsCodeBtn = btn;
    dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer=dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        if (MaxTime<=0) {
            dispatch_source_cancel(_timer);
            //dispatch_release(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //倒计时结束
                _smsCodeBtn =(UIButton*)[self.view viewWithTag:10];
                [_smsCodeBtn setTitle:@"重新获取" forState:UIControlStateNormal];
                [_smsCodeBtn setUserInteractionEnabled:YES];
                
                [_smsCodeBtn setTitleColor:kThemeColor forState:UIControlStateNormal];
                
            });
        }else{
            NSString* strTime=[NSString stringWithFormat:@"%d s ",(int)(MaxTime)];
            dispatch_async(dispatch_get_main_queue(), ^{
                //倒计时
                _smsCodeBtn=(UIButton*)[self.view viewWithTag:10];
                [_smsCodeBtn setTitle:strTime forState:UIControlStateNormal];
                
                //                _smsCodeBtn.backgroundColor =[UIColor colorWithHexString:@"b1b1b1"];
                [_smsCodeBtn setUserInteractionEnabled:NO];
            });
            MaxTime--;
        }
    });
    dispatch_resume(_timer);
    
}
#pragma mark - SEL Methods
- (BOOL)checkParam{
    
    if (self.accountTextFiled.inputTextFiled.text.length < 6 || self.accountTextFiled.inputTextFiled.text.length > 18) {
        [MBProgressHUD LY_ShowError:(@"帐号不符合要求,请重新输入") time:2.0];
        return false;
    }
    if (self.pwdTextField.inputTextFiled.text.length < 6 || self.pwdTextField.inputTextFiled.text.length > 18) {
        [MBProgressHUD LY_ShowError:(@"密码不符合要求,请重新输入") time:2.0];
        return false;
    }
    if (self.rePwdTextField.inputTextFiled.text.length ==0) {
     [MBProgressHUD LY_ShowError:(@"请输入验证码") time:2.0];
        return false;
    }
  
    return YES;
}


- (JYSettingPwdView *)registerFrame:(CGRect)frame placeholder:(NSString *)placeholder leftImgName:(NSString *)leftImgName{
    
    JYSettingPwdView *regiseter = [[JYSettingPwdView alloc] initWithFrame:frame];
    regiseter.inputTextFiled.placeholder = placeholder;
    regiseter.imgView.image = [UIImage imageNamed:leftImgName];
    [self.bgView addSubview:regiseter];
    
    return regiseter;
    
    
}

@end
